package com.xjtu.platform.reader.impl;

import com.xjtu.platform.reader.AsyncService;
import com.xjtu.platform.reader.ReaderService;
import com.xjtu.platform.reader.dao.ReserveDao;
import com.xjtu.platform.reader.dto.BorrowBookDto;
import com.xjtu.platform.reader.entity.SatisfyReserve;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;

@Service
@Transactional
public class AsyncServiceImpl implements AsyncService {

    @Resource
    private ReserveDao reserveDao;

    @Resource
    private ReaderService readerService;
    @Override
    @Async
    public void handleReserveAfterReturn(String bookId) {
        Date date = new Date();
        Timestamp now_time = new Timestamp(date.getTime());
        System.out.println("异步处理预约开始");
        String bookCurrentNum = reserveDao.getBookCurrentNum(bookId);
        System.out.println("量为"+bookCurrentNum);
        SatisfyReserve satisfyReserve = reserveDao.getSatisfiedReserveRecord(bookId,bookCurrentNum);
        if(satisfyReserve != null){
            BorrowBookDto borrowBookDto = new BorrowBookDto();
            borrowBookDto.setBook_id(bookId);
            borrowBookDto.setBorrow_time(satisfyReserve.getBorrow_time());
            borrowBookDto.setBook_num(satisfyReserve.getReserve_num());
            boolean isBorrow = readerService.borrowBook(borrowBookDto, satisfyReserve.getReader_id());
            if(isBorrow){
                reserveDao.handleReserveIfSatisfied(satisfyReserve.getReserve_his_id(),now_time);
                System.out.println("预约转借书成功，记录为: "+satisfyReserve.getReserve_his_id());
            }
        }else {
            System.out.println("没有满足的预约");
        }
    }
}
